//! 线程池管理模块
use crate::config_model::AppConfig;
use crate::do_task::execute_business_logic;
use anyhow::Result;
use common_service::ding_helper::send_msg_to_ding;
use log::{debug, error, info};
use remote_service::{GWebRemoteService, model::SiteInfo};
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::{
    sync::Mutex,
    time::{Duration, sleep},
};

/// 线程池管理器
/// 负责管理线程的生命周期、任务分配和线程替换
#[derive(Clone)]
pub struct ThreadPoolManager {
    pub config: Arc<AppConfig>,                 // 线程池配置
    pub remote_service: Arc<GWebRemoteService>, //远程服务对象
    pub site_info: Arc<SiteInfo>,
    pub startup_lock: Arc<Mutex<()>>,   // 线程锁
    pub active_count: Arc<AtomicUsize>, // 存放空闲线程数量
}

impl ThreadPoolManager {
    /// 创建新的线程池管理器
    /// # 参数
    /// - `config`: 线程池配置
    pub fn new(
        config: Arc<AppConfig>,
        remote_service: Arc<GWebRemoteService>,
        site_info: Arc<SiteInfo>,
    ) -> Self {
        let pool_size = config.thread.pool_size;
        info!("创建新的线程池管理器，线程池大小: {}", pool_size);
        let mut ids = VecDeque::new();
        for i in 1..=pool_size {
            ids.push_back(i);
        }
        Self {
            config,
            remote_service,
            site_info,
            startup_lock: Arc::new(Mutex::new(())),
            active_count: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// 启动线程池
    /// 按照配置的线程数量和初始延迟启动所有线程
    pub async fn start(&self) -> Result<()> {
        debug!("线程池启动，读取配置信息: {:?}", self.config);
        let pool_size = self.config.thread.pool_size;
        // 使用 async for 循环依次启动每个线程
        for _ in 0..pool_size {
            self.start_thread().await?;
        }
        info!("线程池启动完成，总共启动 {} 个线程", pool_size);
        let self_clone = self.clone();
        //线程全部启动完成后，开启异步监测，补充线程
        tokio::spawn(async move {
            loop {
                if self_clone.active_count.load(Ordering::Relaxed) < pool_size {
                    let _ = self_clone.start_thread().await;
                }
                sleep(Duration::from_secs(1)).await; // 每秒检查一次
            }
        });

        Ok(())
    }

    /// 启动新线程（调度器调用）
    async fn start_thread(&self) -> Result<()> {
        let self_clone = self.clone();
        let _ = self.active_count.fetch_add(1, Ordering::SeqCst) + 1;
        tokio::spawn(async move {
            let thread_name = std::thread::current()
                .name()
                .unwrap_or("unnamed")
                .to_string();
            {
                // 使用 scopeguard 库的 defer（推荐）确保线程执行或者panic后线程数量会-1
                scopeguard::defer! {
                let previous_count = self_clone.active_count.fetch_sub(1, Ordering::SeqCst);
                info!("线程 {} 退出，剩余线程数: {}", thread_name, previous_count - 1);
                }
                if let Err(e) = self_clone.perform_task().await {
                    error!("线程 {} 执行任务失败: {:?}", thread_name, e);
                    let _ = send_msg_to_ding(&format!("线程 {} 执行任务失败", thread_name));
                }
                info!("线程 {} 完成", thread_name,);
            } // defer 在这里执行
        });
        Ok(())
    }

    /// 执行任务
    /// # 参数
    /// - `thread_name`: 线程名
    async fn perform_task(&self) -> Result<()> {
        let thread_name = std::thread::current()
            .name()
            .unwrap_or("unnamed")
            .to_string();
        // 任务执行
        let result = execute_business_logic(&self).await;
        match result {
            Ok(_) => {
                info!("任务线程 {} 任务执行完成", thread_name);
                Ok(())
            }
            Err(e) => {
                error!("任务线程 {} 任务执行失败: {:?}", thread_name, e);
                Err(e)
            }
        }
    }
}
